﻿
#region import

using System;
using System.Collections;
using System.Configuration;
using System.Data;
 
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
using System.IO;
using System.Xml;
using System.Collections.Generic;


 
using System.Xml.Serialization;
 
using TimKen.DataAccess;
using TimKen.App;

#endregion  endimort




namespace TimKen.Web.Admin
{
    public partial class SearchWin : AdminPage
    {
        //不同类型的查询操作
        private string[] CHAR_OP = new string[] { "相似于|Like", "等于|=", "不等于|<>", "不相似于|Not Like" };
        private string[] NUM_OP = new string[] { "大于|>", "大于或等于|>=", "等于|=", "不等于|<>", "小于|<", "小于或等于|<=" };
        private string[] DATE_OP = new string[] { "等于|=", "不等于|<>", "先于|<", "后于|>" };


        //数据总数
        public int  total;

        public SearchInfo searchInfo;

        protected void Page_Load(object sender, EventArgs e)
        {
            SearchName = Request.QueryString["ObjectName"];

            Query = Request.QueryString["Query"] == null ? "" : Request.QueryString["Query"];
            MoreSelect = Request.QueryString["MoreSelect"] == null ? false : Convert.ToBoolean(Request.QueryString["MoreSelect"].ToString());

            if (string.IsNullOrEmpty(SearchName))
                throw new ArgumentNullException();

            searchInfo = GetSearchInfo(SearchName);

            if (!IsPostBack)
            {
                BindColumn();
                BindData();
                AddTerm();

            }
        }


        #region  用来保证PostBack时重新加载查询控件


        public bool IsDynamicLoadControl
        {
            get
            {
                object dynamic = ViewState["IsDynamicLoadControl"];
                return dynamic == null ? false : true;
            }
            set
            {
                ViewState["IsDynamicLoadControl"] = value;
            }
        }
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (IsDynamicLoadControl)
            {
                AddTerm();
            }
        }

        #endregion



        public string SearchName
        {
            get
            {
                return ViewState["ObjectName"].ToString();
            }
            set
            {
                ViewState["ObjectName"] = value;
            }
        }


        public string Query
        {
            get
            {
                return ViewState["Query"].ToString();
            }
            set
            {
                ViewState["Query"] = value;
            }
        }
        //判断是否可以多选
        public bool MoreSelect
        {
            get
            {
                return Convert.ToBoolean(ViewState["MoreSelect"].ToString());
            }
            set
            {
                ViewState["MoreSelect"] = value;
            }
        }

        public void BindColumn()
        {
            foreach (Field field in searchInfo.Fields)
            {
                BoundField bfield = new BoundField();
                bfield.HeaderText = field.Name;
                //关联查询前缀问题
                if (field.Value.Contains("."))
                    bfield.DataField = field.Value.Trim().Split('.')[1];
                else
                    bfield.DataField = field.Value.Trim();
                this.GridView1.Columns.Add(bfield);
            }
        }

        public void BindData()
        {
            DataSet ds = GetData();
            AspNetPager1.RecordCount = (int)total;

            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();

            if (this.GridView1.Rows.Count == 0)
                this.Prompt1.Text = "没有数据";
            else
                this.Prompt1.Text = string.Empty;
        }



        public DataSet GetData()
        {
            string whereString = " 1=1 ";
            if (!string.IsNullOrEmpty(Query))
                whereString += "AND " + Query;

            try
            {
                whereString += searchInfo.Where.ToString();

                //获取所有的需要查询的列名
                string columns = "";


                foreach (Field field in searchInfo.Fields)
                    columns += field.Value + ",";

                columns = columns.Substring(0, columns.Length - 1);


                return DbHelperSQL.GetPageList(columns, searchInfo.TableName, whereString, searchInfo.OrderBy, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out total);
            }
            catch (Exception)
            {
                return null;
            }

        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }


        public static List<SearchInfo> GetSearchInfoList()
        {
            List<SearchInfo> SearchInfoList = null;


            if (SearchInfoList == null)
            {
                string path = System.Web.HttpContext.Current.Server.MapPath("~/Admin/SearchXML/SearchInfo.xml");
                //定义流将xml读出来
                using (StreamReader sr = new StreamReader(path))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(List<SearchInfo>));
                    object o = xs.Deserialize(sr);//反序列化成object
                    SearchInfoList = o as List<SearchInfo>;
                }
           
            }
            return SearchInfoList;
        }

        public static SearchInfo GetSearchInfo(string objectName)
        {
            List<SearchInfo> SearchInfoList = GetSearchInfoList();

             return  SearchInfoList.Find(p => p.SearchName == objectName);
 
        }




        /// <summary>
        /// 根据字段获取对应的操作符列表
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>

        public string[] GetOptions(string field)
        {
            string strTypeofField = GetTypeofField(field);
            switch (strTypeofField)
            {
                case "char":
                    return CHAR_OP;
                    break;
                case "int":
           
                        return (new string[] { "是|=", "不是|<>" });
                    
                    break;
                case "decimal":
                    return NUM_OP;
                    break;
                case "datetime":
                    return DATE_OP;
                    break;
                default:
                    return (new string[] { "等于|=" });
                    break;
            }
        }



        public static string[] GetFields(string searchName)
        {
            List<string> result = new List<string>();

            try
            {
                SearchInfo info = GetSearchInfo(searchName);

                foreach (Field field in info.Fields)
                    result.Add(field.Name + "|" + field.Value);
            }
            catch (Exception e)
            {
                throw new ArgumentOutOfRangeException(@"指定的查询不存在，请重新定义XML文档！");
            }
            return result.ToArray();
        }


 



        /// <summary>
        /// 获取字段的数据类型
        /// </summary>
        /// <param name="searchName"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        private string GetTypeofField(string field)
        {
            string strTypeofField = string.Empty;
            try
            {
                SearchInfo info = GetSearchInfo(SearchName);

                foreach (Field f in info.Fields)
                    if (f.Value == field)
                        strTypeofField = f.DataType;
            }
            catch (Exception ee)
            {
                throw new ArgumentOutOfRangeException(@"指定的字段接点不存在，请重新定义XML文档！");
            }

            return strTypeofField.ToLower();
        }




 

        


        /// <summary>
        /// 动态添加查询控件
        /// </summary>
        public void AddTerm()
        {
            if (searchInfo == null)
                searchInfo = GetSearchInfo(SearchName);

            //只获取标识为需要查询的字段


            List<Field> searchFields = searchInfo.Fields.FindAll(p => p.IsSearch = true);

            for (int i = 0; i < searchFields.Count; i++)
            {
                HtmlTableRow tr = new HtmlTableRow();
                HtmlTableCell tc = new HtmlTableCell();

                Field field = searchFields[i];






                //添加查询字段名
                tc = new HtmlTableCell();
                tr.ID = "row" + field.Value;
                tc.InnerText = field.Name;
                tr.Cells.Add(tc);


                //添加用户操作
                string[] options = GetOptions(field.Value);

                DropDownList ddl = new DropDownList();

                ddl.ID = "operation" + field.Value;
                foreach (string option in options)
                {
                    ddl.Items.Add(new ListItem(option.Split('|')[0], option.Split('|')[1]));
                }

                tc = new HtmlTableCell();
                tc.Controls.Add(ddl);

                tr.Cells.Add(tc);



                #region    设置字段条件值的录入（选择）框
                //获取可能存在的枚举值
                

                tc = new HtmlTableCell();

               
                    TextBox tb = new TextBox();
                    tb.ID = "field" + field.Value;


                    //switch (enums[0])
                    //{
                    //    case "int":

                    //}

                    tc.Controls.Add(tb);
                    tr.Cells.Add(tc);
            

           
                this.tbSearch.Rows.Add(tr);

                #endregion


                #region  生成连接条件选择框

                if (i != searchFields.Count - 1)
                {
                    tc = new HtmlTableCell();
                    DropDownList ddlRelate = new DropDownList();
                    ddlRelate.ID = "ddlRelate" + field.Value;
                   
                    ddlRelate.Items.Add(new ListItem("或者", "Or"));
                    ddlRelate.Items.Add(new ListItem("并且", "And"));
                    tc.Controls.Add(ddlRelate);
                    tr.Cells.Add(tc);
                }

                else
                {
                    tc = new HtmlTableCell();
                    tr.Cells.Add(tc);
                }
                #endregion

            }


            if (searchFields.Count != 0)
            {
                Button btnSearch = new Button();
                btnSearch.ID = "btnSearch";
                btnSearch.Text = "查询";
                btnSearch.Click += new EventHandler(btnSearch_Click);

                HtmlTableRow trBtn = new HtmlTableRow();
                trBtn.ID = "rowSearch";


                HtmlTableCell tcBtn = new HtmlTableCell();
                tcBtn.ColSpan = 4;
                tcBtn.Controls.Add(btnSearch);

                trBtn.Cells.Add(tcBtn);
                this.tbSearch.Rows.Add(trBtn);
            }

            IsDynamicLoadControl = true;
        }



        void btnSearch_Click(object sender, EventArgs e)
        {
            if (searchInfo == null)
                searchInfo = GetSearchInfo(SearchName);

            //只获取标识为需要查询的字段
            List<Field> searchFields = searchInfo.Fields.FindAll(p => p.IsSearch = true);



            for (int i = 0; i < searchFields.Count; i++)
            {
                if (i == 0)
                {
                    if (!string.IsNullOrEmpty(Query))
                        Query += " AND ";
                    Query += "(";
                }

                Field sfield = searchFields.ToArray()[i];
                DropDownList ddl = this.Master.FindControl("ContentMain").FindControl("operation" + sfield.Value) as DropDownList;
                string opt = ddl.SelectedValue;
                string field = sfield.Value;

                string inputValue = "";

                if (sfield.Enum == null)
                {
                    TextBox tb = this.Master.FindControl("ContentMain").FindControl("field" + sfield.Value) as TextBox;
                    inputValue = tb.Text;
                }
                else
                {
                    DropDownList ddlOption = this.Master.FindControl("ContentMain").FindControl("options" + sfield.Value) as DropDownList;
                    inputValue = ddlOption.SelectedValue;
                }



                switch (sfield.DataType)
                {
                    case "char":
                        if (string.IsNullOrEmpty(inputValue))
                        {
                            if (opt.ToLower() == "like" || opt.ToLower() == "not like")
                            {
                                inputValue = "'%%'";
                            }
                            else
                            {
                                inputValue = "''";
                            }
                        }
                        else
                        {
                            if (opt.ToLower() == "like" || opt.ToLower() == "not like")
                            {
                                inputValue = "'%" + inputValue + "%'";
                            }
                            else
                            {
                                inputValue = "'" + inputValue + "'";
                            }

                        }
                        break;
                    case "int":
                        if (inputValue == "" || inputValue == null) inputValue = "0";
                        break;
                    case "decimal":
                        if (inputValue == "" || inputValue == null) inputValue = "0";
                        break;
                    case "datetime":
                        if (inputValue == "" || inputValue == null)
                        {
                            inputValue = "''";
                        }
                        else
                        {
                            inputValue = "'" + inputValue + "'";
                        }
                        break;
                    default:
                        break;
                }

                string jointMode = "";
                if (i != searchFields.Count - 1)
                {
                    DropDownList ddlRelate = this.Master.FindControl("ContentMain").FindControl("ddlRelate" + sfield.Value) as DropDownList;
                    jointMode = ddlRelate.SelectedValue;
                }
                Query += "  " + sfield.Value + " " + opt + " " + inputValue + " " + jointMode;

                if (i == searchFields.Count - 1)
                    Query += ")";
            }
            BindData();
        }



    }





    #region  查询实体信息


    [Serializable]

    public class SearchInfo
    {
        public string SearchName { get; set; }
        public string TableName { get; set; }


        //public string Field { get; set; }
        //public string GridColumn { get; set; }

        public string Where { get; set; }
        public string OrderBy { get; set; }

        public string ReturnField { get; set; }


        public List<Field> Fields { get; set; }

    }



    [Serializable]
    public class Field
    {
        [XmlAttribute(AttributeName = "Name")]
        public string Name { get; set; }

        [XmlAttribute(AttributeName = "Value")]
        public string Value { get; set; }

        [XmlAttribute(AttributeName = "DataType")]
        public string DataType { get; set; }

        public Enum Enum { get; set; }

        [XmlAttribute(AttributeName = "IsSearch")]
        public bool IsSearch { get; set; }
    }


    [Serializable]
    public class Enum
    {
        [XmlAttribute(AttributeName = "SqlSyntax")]
        public string SqlSyntax { get; set; }

        [XmlAttribute(AttributeName = "TextField")]
        public string TextField { get; set; }

        [XmlAttribute(AttributeName = "ValueField")]
        public string ValueField { get; set; }
    }

    #endregion


}
